/** 
 * Project Name:kaka 
 * File Name:OAuthAction.java 
 * Package Name:com.luoran.kaka.oauth 
 * Date:2018年12月5日下午6:56:54 
 * Copyright (c) 2018, Luoran, Inc. All Rights Reserved.
 * 
 */
package com.luoran.kaka.oauth;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.luoran.kaka.entity.WxUserInfo;
import com.luoran.kaka.service.IWxUserInfoService;
import com.luoran.kaka.utils.ReadUrlUtil;

/** 
 * ClassName: WeChatOAuthAction
 * date: 2018年12月5日 下午6:56:54
 * @author ghl 
 * @since JDK 1.8
 * 第三方网页获取微信授权
 */

@Controller
@RequestMapping("/wechat")
public class WeChatOAuthAction {

	public static final Logger log = LoggerFactory.getLogger(WeChatOAuthAction.class);
	
	@Autowired
	private IWxUserInfoService wxUserInfoService;

	@Autowired
	private Environment evi;

	/** 
	 * 
	 * @author ghl 2018年12月6日下午12:53:18
	 * @param request
	 * @param response
	 * @throws Exception 
	 * @since JDK 1.8
	 * wechatOAuth:跳转到微信用户授权,用户点击通用可以获取微信授权,拿到用户信息
	 */
	@RequestMapping("/auth")
	@ResponseBody
	public void wechatOAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.info("跳转到请求微信用户授权页面，请求地址为：{}",request.getRequestURL().toString());
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		String projectPath = evi.getProperty("project.path");
		String appId = evi.getProperty("wechat.appid");
		String authUri = evi.getProperty("wechat.authorize");
		/**
		 * 第一步：用户同意授权，获取code:
		 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
		 */
		String redirect_uri = URLEncoder.encode(projectPath + "/kaka/wechat/login", "UTF-8");// 授权后重定向的回调链接地址，请使用URLEncode对链接进行处理（文档要求）
		log.info("授权后重定向的回调链接地址为：{}", redirect_uri);
		// 按照文档要求拼接访问地址
		String url = authUri + "?appid=" + appId + "&redirect_uri=" + redirect_uri
				+ "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		log.info("跳转要访问的地址为：{}", url);
		response.sendRedirect(url);// 跳转到要访问的地址
	}


	/** 
	 * 
	 * @author ghl 2018年12月6日下午1:17:37
	 * @param request
	 * @throws JSONException
	 * @throws IOException 
	 * @since JDK 1.8
	 * login:用户同意授权操作后调转到此请求,参数中可以获取code.
	 */
	@RequestMapping("/login")
	@ResponseBody
	public void login(HttpServletRequest request,Model model,HttpServletResponse response) throws JSONException, IOException {
		String code = request.getParameter("code");
		if (!StringUtils.isEmpty(code)) {
			log.info("获取code成功，code为：{}", code);
		} else {
			log.info("网络异常,获取code失败.");
		}
		String appId = evi.getProperty("wechat.appid");
		String appSecret = evi.getProperty("wechat.appsecret");
		String accessTokenUri = evi.getProperty("wechat.accesstoken");
		String userInfoUri = evi.getProperty("wechat.userinfo");
		String projectPath = evi.getProperty("project.path");
		/**
		* 第三步：获取code后，请求以下链接获取access_token：  
		* https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		* 通过code换取网页授权access_token
		*/
		// 同意授权
		if (code != null) {
			// 拼接请求地址
			String url = accessTokenUri + "?appid=" + appId + "&secret=" + appSecret + "&code=" + code
					+ "&grant_type=authorization_code";
			log.info("获取access_token的请求地址为：{}", url);
			JSONObject json = ReadUrlUtil.readJsonFromUrl(url);// 获取返回值
			log.info("接口返回access_token数据为：{}", json);
			ParamsResult paramsResult = (ParamsResult) JSONObject.parseObject(json.toJSONString(),
					ParamsResult.class);
			/**
			 * 第四步：拉取用户信息(需scope为 snsapi_userinfo)
			 */
			String userInfoUrl = userInfoUri + "?access_token=" + paramsResult.getAccess_token() + "&openid="
					+ paramsResult.getOpenid() + "&lang=zh_CN";
			log.info("获取用户信息的请求地址为：{}", userInfoUrl);
			JSONObject result = ReadUrlUtil.readJsonFromUrl(userInfoUrl);// 获取返回值
			log.info("接口返回用户信息的数据为：{}", result);
			if(result.containsKey("errcode")) {
				log.info("网络异常");
			}else {
				WxUserInfo wxUserInfo = JSONObject.parseObject(result.toJSONString(), WxUserInfo.class);
				wxUserInfoService.SyncWxUserInfo(wxUserInfo);
				response.sendRedirect(projectPath+"/kaka/card/my/"+wxUserInfo.getOpenid()+"?_t="+System.currentTimeMillis());
			}
		}
	}

}
